package com.itools.core.ucenter.controller;

import com.itools.core.base.CommonResult;
import com.itools.core.ucenter.em.UcenterCodeBean;
import com.itools.core.exception.AppException;
import com.itools.core.ucenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Map;

@Slf4j
@RestController
public class UserLoginController {
    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private UserService userService;
    @GetMapping("/user")
    public Principal user(Principal user){
        return user;
    }

    @RequestMapping(value = "/oauth/token", method= RequestMethod.GET)
    public CommonResult<OAuth2AccessToken> getAccessToken(Principal principal,
                                                          @RequestParam Map<String, String> parameters){

        userService.verifyUserByPasswordType(parameters);
        try {
            //验证用户、设备、密码强度 等登录信息
            return CommonResult.success(tokenEndpoint.getAccessToken(principal,parameters).getBody());
        }catch (Exception e){
            log.error("登录失败：",e);
            throw new AppException(UcenterCodeBean.UcenterCode.FAIL_LOGIN.code);
        }
    }

    @RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
    public CommonResult<OAuth2AccessToken> postAccessToken(Principal principal,
                                                           @RequestParam Map<String, String> parameters){
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        userService.verifyUserByPasswordType(parameters);
        try {
            return CommonResult.success(tokenEndpoint.postAccessToken(principal,parameters).getBody());
        }catch (Exception e){
            log.error("登录失败：",e);
            throw new AppException(UcenterCodeBean.UcenterCode.FAIL_LOGIN.code);
        }
    }
}
